package com.yueqian.dao;

import com.yueqian.domain.Role;
import com.yueqian.domain.UserInfo;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface IUserDao {
    //根据用户名查询用户信息,同时将用户所对应的角色信息查出来
    @Select("select * from users where username=#{username}")
    @Results({
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "username", property = "username"),
            @Result(column = "email", property = "email"),
            @Result(column = "password", property = "password"),
            @Result(column = "phoneNum", property = "phoneNum"),
            @Result(column = "status", property = "status"),
            @Result(column = "id", property = "roles",
                    many = @Many(select = "com.yueqian.dao.IRoleDao.findRoleByUserId", fetchType = FetchType.LAZY))
    })
    UserInfo findUserByUserName(String username) throws Exception;


    /**
     * 查询所有用户
     *
     * @return
     */
    @Select("select * from users")
    List<UserInfo> findAll() throws Exception;

    @Insert("insert into users(email,username,password,phoneNum,status) values(#{email},#{username},#{password},#{phoneNum},#{status})")
    void save(UserInfo userInfo) throws Exception;

    @Select("select * from users where id=#{id}")
    @Results({
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "username", property = "username"),
            @Result(column = "email", property = "email"),
            @Result(column = "password", property = "password"),
            @Result(column = "phoneNum", property = "phoneNum"),
            @Result(column = "status", property = "status"),
            @Result(column = "id", property = "roles",
                    many = @Many(select = "com.yueqian.dao.IRoleDao.findRoleByUserId", fetchType = FetchType.LAZY))
    })
    UserInfo findById(String id) throws Exception;

    /*
    根据用户id查询没有关联的角色的集合
     */
    @Select("select * from role where id not in(select roleid from users_role where userid=#{id})")
    List<Role> findUserAndNoRole(String id) throws Exception;

    //给中间表插入数据
    @Insert("insert into users_role(userId,roleId) values(#{arg0},#{arg1})")
    void addRoleToUser(String userId, String roleId) throws Exception;
}
